package com.gitee.dufafei.plugin.core;

import java.net.URL;
import java.net.URLClassLoader;

public class PluginURLClassLoader extends URLClassLoader {

    private String name;

    public PluginURLClassLoader(URL[] url, ClassLoader classLoader) { super(url, classLoader); }

    public PluginURLClassLoader(URL[] url, ClassLoader classLoader, String name) {
        this(url, classLoader);
        this.name = name;
    }

    public void setName(String name) { this.name = name; }

    public String getName() { return name; }

    @Override
    protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        try {
            return loadClassFromThisLoader(name, resolve);
        } catch (ClassNotFoundException | NoClassDefFoundError e) {
            return loadClassFromParent(name, resolve);
        }
    }

    public Class<?> loadClassFromThisLoader(String name, boolean resolve) throws ClassNotFoundException {
        Class<?> clz = findLoadedClass(name);
        if (clz == null) {
            clz = findClass(name);
        }
        if (clz != null && resolve) {
            resolveClass(clz);
        }
        return clz;
    }

    public Class<?> loadClassFromParent(String name, boolean resolve) throws ClassNotFoundException {
        Class<?> clz = getParent().loadClass(name);
        if (clz != null) {
            if (resolve) {
                resolveClass(clz);
            }
            return clz;
        } else {
            throw new ClassNotFoundException("Could not find :" + name);
        }
    }

    @Override
    public URL getResource(String name) {
        URL url = findResource(name);
        if (url == null && getParent() != null) {
            url = getParent().getResource(name);
        }
        return url;
    }

    @Override
    public String toString() { return super.toString() + ": " + name; }
}